package com.gome.wechat.program.common.util;



import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.apache.commons.lang3.RandomStringUtils.*;


/**
 * Created by lw on 2014-10-04.
 */
public final class ToolUtils {

    private static final Logger logger = LoggerFactory.getLogger(ToolUtils.class);

    private static final char[] chars=new char[] {
            'a' ,'b' ,'c' ,'d' ,'e' ,'f' ,'g' ,'h' ,'i' ,'j' ,'k' ,'l' ,
            'm' ,'n' ,'o' ,'p' ,'q' ,'r' ,'s' ,'t' ,'u' ,'v' ,'w' ,'x' ,
            'y' ,'z' ,'0' ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,
            'A' ,'B' ,'C' ,'D' ,'E' ,'F' ,'G' ,'H' ,'I' ,'J' ,'K' ,'L' ,
            'M' ,'N' ,'O' ,'P' ,'Q' ,'R' ,'S' ,'T' ,'U' ,'V' ,'W' ,'X' ,
            'Y' ,'Z'};

    /**
     * 数字的ascii码范围
     */
    private static final char numberCodeBegin=48;
    private static final char numberCodeEnd=57;
    /**
     * 大写字母的ascii码范围
     */
    private static final char upperCaseCodeBegin=65;
    private static final char upperCaseCodeEnd=90;
    /**
     * 小写字母的ascii码范围
     */
    private static final char lowerCaseCodeBegin=97;
    private static final char lowerCaseCodeEnd=122;
    /** 配置A-Z,0-9和_ **/
    private static Pattern PINGYIN_ESCAPE = Pattern.compile("\\w");

    /**
     * 生成TEAMID的短码，如：TcYUtgY，统一以“T”打头，第二位是校验码，后面5位是数字的62进制
     * @param teamId
     * @return
     */
    public static  String buildTeamShortCode(int teamId){
        if(teamId>=900000000){
            throw new RuntimeException(String.format("输入值%d应小于900000000",teamId));
        }else {
            char[] result={'a','a','a','a','a'};
            teamId=900000000-teamId;
            String s = get62HEXString(teamId);
            for(int i=0;i<s.length();i++){  //将Z3拼成aaaZ3
                result[5-s.length()+i]=s.charAt(i);
            }
            int asc=0;
            for(int i=0;i<result.length;i++){
                asc+=result[i];
            }
            int temp=getIntBy64HEXChar(result[4]);
            if(temp==0){
                temp=62;
            }
            String resultStr=chars[asc%temp]+new String(result);
            return resultStr;
        }
    }

    /**
     * 根据字符串短码生成整型
     * @param shortCode 格式为“cYUtgY”
     * @return
     */
    public static  int getTeamIdByShortCode(String shortCode){
        if(FStringUtils.asString(shortCode).length()!=6){
            throw new RuntimeException(String.format("输入字符串%s长度应等于6",shortCode));
        }else {
            //合法性校验
            String s=shortCode.substring(1);
            int asc=0;
            for(int i=0;i<s.length();i++){
                asc+=s.charAt(i);
            }
            int temp=getIntBy64HEXChar(shortCode.charAt(5));
            if(temp==0){
                temp=62;
            }
            if(chars[asc%temp]!=shortCode.charAt(0)){
                throw new RuntimeException(String.format("输入字符串%s不合法",shortCode));
            }else {
                return 900000000 - getIntBy62HEXString(s);
            }
        }
    }

    /**
     * 根据62进制的字符，返回对应的十进制值
     * @param ch
     * @return
     */
    private static int getIntBy64HEXChar(char ch) {
        int num = 0;
        if(ch >= 'A' && ch <= 'Z') {
            num = ch - 'A' +36 ;
        } else if(ch >= 'a' && ch <= 'z') {
            num = ch - 'a';
        } else {
            num = ch - '0'+26;
        }
        return num;
    }

    /**
     * 根据62进制的字串，返回整数
     * @param s
     * @return
     */
    public static int getIntBy62HEXString(String s){
        int len = s.length();
        int temp=0;
        for(int i =0; i <len; i++) {
            int t = getIntBy64HEXChar(s.charAt(i));
            temp=temp+t*(int)Math.pow(62,len-i-1);
        }
        return temp;
    }

    /**
     * 生成62进制字符串
     * @param value
     * @return
     */
    public static String  get62HEXString(int value){

        StringBuffer sb=new StringBuffer(16);
        // int i=0;
        while(value>0){
            int temp =value%62;
            value=value/62;
            sb.append(chars[temp]);  //先存低位
        }
        return sb.reverse().toString();
    }
    /**
     * 生成4位随访数字
     * @return
     */
    public static   String getRandCode() {
        return String.valueOf(RandomUtils.nextInt(1234, 9999));
    }

    /**
     * 生成指定位数的随访数字
     * @return
     */
    public static   String getRandCode(int length) {
        int begin = (int) (Math.pow(10, length-1) + 1);
        int end = (int) (Math.pow(10, length) - 1);

        return String.valueOf(RandomUtils.nextInt(begin, end));
    }

    /**
     *随机生成长度为8的字符串
     * @return
     */
    public static String randShortURLCode() {
        return random(8, chars);
    }

    /**
     * 生成指定长度的字串
     * @param length
     * @return
     */
    public static String randShortURLCode(int length) {
        return random(length, chars);
    }

    /**
     * 检查URL短码的有效性
     * @param code
     * @return
     */
    public static Boolean checkShortURLCodeAvailable(String code)
    {
        if(code.length()!=8) return false;
        for(int i=0;i<code.length();i++)
        {
            if(!(
                    (code.charAt(i)>=ToolUtils.numberCodeBegin&&code.charAt(i)<=ToolUtils.numberCodeEnd)
                            ||(code.charAt(i)>=ToolUtils.upperCaseCodeBegin&&code.charAt(i)<=ToolUtils.upperCaseCodeEnd)
                            ||(code.charAt(i)>=ToolUtils.lowerCaseCodeBegin&&code.charAt(i)<=ToolUtils.lowerCaseCodeEnd)
            ))
                return false;
        }
        return true;
    }

    /**
     * 把用分隔符组成的字符串生成一个List,去掉重复值
     *
     * @param ids
     * @param separator
     * @return
     */
    public static List<Long> getIdsFromStr(String ids,String separator){
        if(StringUtils.isNotBlank(ids)) {
            if(ids.contains("[")){
                ids = ids.substring(1,ids.length()-1);
            }
            //去掉多余的分隔符
            ids = StringUtils.join(StringUtils.split(ids, separator), separator);

            List<Long> ids_long = new ArrayList<>();
            String[] idsStr = ids.split(separator);
            for (String caseIdStr : idsStr) {
                try {
                    Long temp = Long.parseLong(caseIdStr);
                    if (!ids_long.contains(temp)) {
                        ids_long.add(temp);
                    }
                }catch (Exception e)
                {
                    logger.error(String.format("将字串转换成数字失败%s",ids));
                }
            }
            return ids_long;
        }else
            return new ArrayList<>();
    }


    /*
    * 字符串操作：将“a,b,c”转换为“'a','b','c'”
    *
    * */
    public static String stringToSqlInGrammer(String ids){
        if(!FStringUtils.isValid(ids)||",".equals(ids)){
            return  "''";
        }
        String s="";
        List<String> ls = Arrays.asList(ids.split(","));
        for (int i = 0; i < ls.size(); i++) {
            s+="'"+ls.get(i)+"'";
            if(i<ls.size()-1){
                s+=",";
            }
        }
        return s;
    }
    /*
    * 将List<String> ->  'a','b','c'
    * */
    public static  String  longList2InGrammer(List<Long> ids){
        if(ids==null||ids.size()==0){
            return "''";
        }
        String s = "";
        for (int i = 0; i < ids.size(); i++) {
            s +="'"+ids.get(i)+"'";
            if(i<ids.size()-1)
                s+=",";
        }
        return s;
    }

    /*
   * 将List<String> ->  'a','b','c'
   * */
    public static  String  integerList2InGrammer(List<Integer> ids){
        if(ids==null||ids.size()==0){
            return "''";
        }
        String s = "";
        for (int i = 0; i < ids.size(); i++) {
            s +="'"+ids.get(i)+"'";
            if(i<ids.size()-1)
                s+=",";
        }
        return s;
    }

    public static String covertSpecialChar(String s){
        if(!FStringUtils.isValid(s)){
            return "";
        }
        String result = s.replaceAll("'", "\\\\'");
        return result;
    }






    public static String  readHtml(String htmlurl) {
        URL url;
        String temp;
        final StringBuffer sb = new StringBuffer();
        try
        {
            url = new URL(htmlurl);
            final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));// 读取网页全部内容
            while ((temp = in.readLine()) != null)
            {
                sb.append(temp);
            }
            in.close();
        } catch (final MalformedURLException me)
        {
            System.out.println("你输入的URL格式有问题！请仔细输入");

        }
        catch (final IOException e)
        {
            e.printStackTrace();
        }
        return sb.toString();
    }
    public static String delHTMLTag(String htmlStr){
        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
        String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式

        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
        Matcher m_script=p_script.matcher(htmlStr);
        htmlStr=m_script.replaceAll(""); //过滤script标签

        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
        Matcher m_style=p_style.matcher(htmlStr);
        htmlStr=m_style.replaceAll(""); //过滤style标签

        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
        Matcher m_html=p_html.matcher(htmlStr);
        htmlStr=m_html.replaceAll("").trim().replaceAll(" ","").replaceAll("\n","").replaceAll("\t","");; //过滤html标签
        List<String> contents =Arrays.asList(htmlStr.split(""));
        return contents.get(contents.size() - 1);
    }


    public static String handleSqlParams(String sources){
        if(StringUtils.isNotBlank(sources)){
            if("''".equals(sources)){
                return sources;
            }
            sources = sources.replace("'","");
            sources = sources.replace("%","/%");
            return sources;
        }
        return "";
    }

    public static int[] transform(List<Integer> dataList){
        int[] result = new int[0];
        if(CollectionUtils.isEmpty(dataList)){
            return result;
        }
        int size = dataList.size();
        result = new int[size];
        for(int i = 0;i<size;i++){
            result[i] = dataList.get(i);
        }
        return result;
    }

    public static Object[] transformObject(List<Object> dataList){
        Object[] result = new Object[0];
        if(CollectionUtils.isEmpty(dataList)){
            return result;
        }
        int size = dataList.size();
        result = new Object[size];
        for(int i = 0;i<size;i++){
            result[i] = dataList.get(i);
        }
        return result;
    }

    public static String handleRichText(String richText){
        if(StringUtils.isBlank(richText)){
            return "";
        }
        String result = richText.replaceAll("</?[^>]+>", "");
        result = result.replaceAll("<a>\\s*|t|r|n</a>", "");
        result = result.replace("&amp;"," ").replace("&nbsp;","");

        return result;
    }

}
